var CACHE_URL = '';

$(function(){
	//图片自动居中
	$(".auto_img").auto_img();
	
//	$(".picture_selector").
//	$(".ajax_upload_btn").ajax_upload({
//		
//	});
//	if($('#i_wrap').length){
//		$('#i_wrap').jScrollPane();
//	}
	
});

function show_loading(options){
	var opts = {
		info : '<div class="loading_info_div"><img src="/template/images/loading_2.gif" class="loading_icon">正在处理，请稍候...</div>'
	};
	options = $.extend(opts, options);
	if(!$('#loading_div').length){
		$("body").append('<div id="loading_div"></div>');
	}
	$('#loading_div').html(options.info).dialog({
		modal : true,
		title : '系统提示',
		dialogClass : 'loading_dialog'
	});
}

function close_loading(){
	$('#loading_div').dialog('destroy');
}

function init_kindEditor_editor(textarea_obj){
	KindEditor.ready(function(K) {
		create_editor(textarea_obj);
	});
}

function create_editor(textarea_obj){
	KindEditor.create(textarea_obj, {
		items : [
	         "undo", "redo", "|", "preview", "print", "template", "cut", "copy", "paste",
	         "plainpaste", "wordpaste", "|", "justifyleft", "justifycenter", "justifyright",
	         "justifyfull", "insertorderedlist", "insertunorderedlist", "indent", "outdent", "subscript",
	         "superscript", "clearhtml", "quickformat", "selectall", "|", "fullscreen",
	         "formatblock", "fontname", "fontsize", "|", "forecolor", "hilitecolor", "bold",
	         "italic", "underline", "strikethrough", "lineheight", "removeformat", "|", "image",
	         "flash", "media", "insertfile", "table", "hr", "emoticons", "map", "code", "pagebreak",
	         "link", "unlink" 
         ],
     	syncType:'form',
     	afterBlur:function(){
			this.sync();
		},
		afterCreate:function(){
			$(this.container).removeAttr("style");
		},
		cssPath : CACHE_URL + "/template/js/editor/kindEditor/plugins/code/prettify.css",
		uploadJson : "/index.php?app=site&act=upload",
		fileManagerJson : "/index.php?app=site&act=file_manager",
		allowFileManager : true
	});
}

var img_size_reg = /.*?\/?(\d+)x(\d+)\/.*/ig;
var picture_selector_onselect = null;
jQuery.fn.extend({
//	scroll_nav : function(){
//		return this.each(function(i){
//			var base_top = $('.main_content').offset().top;
//			var top = $(this).offset().top;
//			var left = $(this).offset().left;
//			var obj = this;
//			$(document).scroll(function(){
//				var s_top = $(document).scrollTop();
//				if(s_top>top){
//					$(obj).css({'position':'fixed', 'top':top-base_top});
//				}else{
//					$(obj).css({'position':'relative'});
//				}
//			});
//		});
//	},
	
	//在item上面添加删除菜单
	item_deleter:function(options){
		var opts = {
			del:false
		};
		options = $.extend(opts, options);
		return this.each(function(i){
			if($(this).find('.edit_div').length)return;
			var img_wrap = this;
			var edit_div = $('<div class="edit_div"></div>');
			if(options.del!==false){
				var del_opt = $('<a href="javascript:void(0)">删除</a>').click(function(){
					options.del(img_wrap);
				});
				edit_div.append(del_opt);
			}
			
			$(this).append(edit_div).hover(function(){
				$(this).find('.edit_div').show();
			},function(){
				$(this).find('.edit_div').hide();
			});
		});
	},
	//图片选择器
	picture_selector:function(options){
		var opts = {
			multiple : true,		//支持多个图片
			on_select : function(selected_imgs){}//选中之后
		};
		options = $.extend(opts, options);
		picture_selector_onselect = options.on_select;
		var dialog_options = {title:'图片选择器 - ' + (options.multiple?'多选':'单选'),width:800,height:550,modal:true};
		return this.each(function(i){
			$(this).click(function(){
				if(!$('#picture_selector').length){
					$('<div id="picture_selector" class="dialog"></div>')
						.html('正在加载...')
						.load('/index.php?app=image&act=selector&multiple='+(options.multiple?1:0))
						.appendTo('body').dialog(dialog_options);
				}else{
					$('#picture_selector').dialog(dialog_options);
				}
				
			});
		});
	},
	ajax_upload : function(options){
		var opts = {
			//开始上传时执行的，一般是显示正在上传提示
			on_upload : function(handle){
				$(handle).val('正在上传...');
			},
			//上传成功时操作
			success : function(handle, json){
				alert('上传成功');
				$(handle).val('添加图片');
			},
			fail : function(handle, json){
				alert(json.info);
			},
			upload_url : '/index.php?app=image&act=upload',
		};
		options = $.extend(opts, options);
		return this.each(function(i){
			var upload_btn = this;
			new AjaxUpload(this,{
		        action: options.upload_url,
		        name: 'imgFile',
		        autoSubmit: true,
		        onSubmit : function(file, ext){
	                if (ext && /^(jpg|png|jpeg|gif)$/.test(ext)){
	                    this.setData({
	                        'info': '文件类型为图片'
	                    });
	                } else {
	                    alert('非图片类型文件！');
	                    return false;              
	                }
	                options.on_upload(upload_btn);
		            this.disable();
		        },
		        onComplete: function(file, response){
		            var json = eval('('+response+')');
		            if(json.result){
		            	options.success(upload_btn, json);
		            }else{
		            	options.fail(upload_btn, json);
		            }
		            this.enable();
		        }
		    });
		});
	},
	auto_img : function(options){
		var opts = {
			ready:function(obj, index){},
			on_delete : function(index, img_wrap){
				alert(index);
				$(img_wrap).remove();
			} //删除事件
		};
		options = $.extend(opts, options);
		return this.each(function(i){
			var src = $(this).attr('src');
			if(!src.match(img_size_reg)){
				return;
			}
			var width = parseInt(src.replace(/.*?\/?(\d+)x(\d+)\/.*/ig, "$1")) + 2;
			var height = parseInt(src.replace(/.*?\/?(\d+)x(\d+)\/.*/ig, "$2")) + 2;
			if($(this).parents('.img_wrap').length){
				$(this).parents('.img_wrap').css({height:height, width:width});
			}else{
				$(this).wrap('<i class="img_wrap" style="height:' + height + 'px;width:' + width + 'px"></i>');
			}
			var image = new Image();
			var obj = this;
			image.src = src;
			$(image).load(function(){
				var img_height = image.height;//图片高
				if(height > img_height && img_height > 0){
					$(obj).css({'margin-top': (height - img_height)/2});
				}
				
				var img_wrap = $(obj).parent();
				options.ready(img_wrap, i);
				if($(obj).hasClass('delete_able')){
					$(img_wrap).item_deleter({
						del:function(img_wrap){
							
							options.on_delete($(img_wrap).index(), img_wrap);
						}
					});
				}
			});
		});
	},
	drop_menu : function(options){
		var opts = {
			ready : function(src, contner){},//初始化好的时候执行
			close : function(src, contner){},//关闭或者隐藏的时候执行
			speed : 500,		//鼠标离开多久后关闭此菜单
			contner_class : 'cate_list_options'	//下拉菜单样式
		};
		options = $.extend(opts, options);
		return this.each(function(i){
			$(this).click(function(){
				var top = $(this).offset().top;
				var left = $(this).offset().left;
				var height = $(this).height();
				var cate_list_div = $('.cate_list_div');
				var ready4close = false;
				var interval_obj = null;
				var id = "m_" + (Math.random() + "").substring(3,5);
				var src = this;
				if(!cate_list_div.length){
					//如果不存在
					cate_list_div = $('<div id="' + id + '" class="' + options.contner_class + '">loading...</div>');
					$('body').append(cate_list_div);
				}
				interval_obj = setInterval(function(){
					if(ready4close){
						options.close(src, cate_list_div);
						cate_list_div.hide();
						clearInterval(interval_obj);
						ready4close = false;
					}
				}, options.speed);
				cate_list_div.css({top:top + height,left:left}).show().hover(function(){
					ready4close = false;
				},function(){
					ready4close = true;
				});
				options.ready(src, cate_list_div);
			});
		});
	},
	//ajax提交
	ajax_form : function(opts){
		var default_opts = {
			'submit_btn' : '.submit',
			'is_alert' : true,
			'info_show_time' : 4,
			'success' : function(form, data){
				var return_url = $(form).attr('url');
				//成功
				if(return_url!=null && return_url!=''){
					window.location.href = return_url;//刷新界面
				}else{
					window.location.reload();
				}
			}
		};
		opts = $.extend(default_opts, opts);
		return this.each(function(i){
			var ajax_form = $(this).css({position:'relative'});
			var busy = false;
			var options = {
				dataType : 'json',
				success : function(data){
					busy = false;
					ajax_form.find('.info').html(data.info);
					if(opts.is_alert){
						alert(data.info);
					}
					if(data.result){
						//成功
						opts.success(ajax_form, data);
					}else{
						//失败
						ajax_form.find('.info').html(data.info).show();
					}
					if(opts.info_show_time>0){
						setTimeout(function(){
							ajax_form.find('.info').fadeOut();
						},opts.info_show_time * 1000);
					}
				}
			};
			ajax_form.ajaxForm(options);
			var info_box = $('<div class="info ui-state-highlight ui-corner-all"></div>').hide().css({position:'absolute',top:0,right:0}).appendTo(ajax_form);
			ajax_form.find(opts.submit_btn).click(function(){
				if(busy)return;
				busy = true;
				info_box.html('正在提交，请稍候...').show();
				ajax_form.submit();
				if($(this).attr('type') == 'submit'){
					return false;
				}
			});
		});
	},
	//带有添加、删除功能的下拉框，见文章编辑中的分类选择框
	yu_selector : function(opts){
		var default_opts = {
			'del_val' : -1,
			'on_del' : function(selector){
				$(selector).remove();
			},
			'on_change' : function(selector){
				
			},
			'add_text' : '添加',
			'add_btn' : true,
			'del_text' : '--删除--'
		};
		opts = $.extend(default_opts, opts);
		var len = this.length;
		var selectors = $(this);
		var src_selector = selectors[0];
		var add_btn = null;
		return this.each(function(i){
			if(i == len - 1){
				if(opts.add_btn){
					var last_selector = this;
					add_btn = $('<a href="javascript:void(0)">' + opts.add_text + '</a>').click(function(){
						var new_selector = $(src_selector).clone();
						var del_opt = $('<option value="-1">' + opts.del_text + '</option>');
						new_selector.append(del_opt);
						$(add_btn).before(new_selector);
						new_selector.yu_selector({on_change : opts.on_change, add_btn:false});
					});
					$(last_selector).after(add_btn);//添加按钮
				}
			}
			$(this).change(function(){
				var v = $(this).val();
				if(v == opts.del_val){
					opts.on_del(this);
				}
				opts.on_change(this);
			});
		});
	}
});